package com.ate.special3;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author Ate
 * @description: 1.礼物停留3秒后消失
 * 2.礼物同时只显示3个  为防止消息丢失，需要做一个消息队列缓存这些消息，定时遍历消息队列
 * 3.数字连击的动画，进行追加，礼物正处于连击中，或者连击未完成用户又送了，需要做一个追加
 * @date :2020/11/18 10:06
 */
public class AnimationManager {
    //礼物飞出的动画
    private static Animation giftOutAnim;

    private static Context mContext;

    //礼物定时器，用于清除和从队列中取礼物
    private static Timer giftClearTimer;

    //礼物队列
    private static ArrayList<AnimMessage> giftList = new ArrayList<>();

    //礼物容器
    private static LinearLayout animViewContainer;

    //礼物定时器执行的间隔
    private static final int GIFT_CLEAR_TIMER_INTERVAL = 1500;

    //礼物无更新后存在的时间
    private static final int GIFT_CLEAR_INTERVAL = 3000;

    //同时存在放的最大礼物数
    private static final int GIFT_MAX_NUMBER = 3;

    //init动画和Context
    public static void init(Context context) {
        mContext = context;
        giftOutAnim = AnimationUtils.loadAnimation(context, R.anim.gift_out);
    }

    /**
     * 添加礼物的linearlayout  container
     *
     * @param linearLayout
     */
    public static void addGiftContainer(LinearLayout linearLayout) {
        if (linearLayout == null || linearLayout.getOrientation() == LinearLayout.HORIZONTAL) {
            return;
        }
        animViewContainer = linearLayout;
    }

    /**
     * 将动画信息添加到队列
     *
     * @param animMessage
     */
    public static void addAnimalMessage(AnimMessage animMessage) {
        if (animMessage != null) {
            giftList.add(animMessage);
            if (giftClearTimer == null && animViewContainer != null && mContext != null) {
                startTimer();
            }
        }
    }

    /**
     * 添加动画View
     */
    private static View addAnimalView(AnimMessage animMessage) {
        return new GiftView(mContext, animMessage);
    }

    private static void removeAnimalView(final int index) {
        if (index >= animViewContainer.getChildCount()) {
            return;
        }
        final View removeView = animViewContainer.getChildAt(index);
        giftOutAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        animViewContainer.removeViewAt(index);
                    }
                });
                //释放资源  将giftClearTimer清空
                if (giftList.size() == 0 && animViewContainer.getChildCount() == 0 && giftClearTimer != null) {
                    giftClearTimer.cancel();
                    giftClearTimer = null;
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        ((Activity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                removeView.startAnimation(giftOutAnim);
            }
        });

    }

    /**
     * 定时清除礼物
     * 使用list作为消息队列，使用定时器来清除当前已经展示完毕的view并从消息队列中取出消息，添加新的view
     * uptime是指暴击结束之后的时间  它需要不断更新
     * 但是更新的频率不能小于定时器的间隔  否则会被当做已经展示完毕的view被清除掉
     */
    private static void startTimer() {
        giftClearTimer = new Timer();
        giftClearTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                int count = animViewContainer.getChildCount();
                //清除礼物
                for (int i = 0; i < count; i++) {
                    View view = animViewContainer.getChildAt(i);
                    AnimMessage message = (AnimMessage) view.getTag();
                    long nowTime = System.currentTimeMillis();
                    long upTime = message.getUpdateTime();
                    if ((nowTime - upTime) >= GIFT_CLEAR_INTERVAL) {
                        removeAnimalView(i);
                        return;
                    }
                }

                //添加礼物
                if (count < GIFT_MAX_NUMBER) {
                    if (giftList.size() > 0) {
                        ((Activity) mContext).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                startGiftAnim(giftList.get(0));
                                giftList.remove(0);
                            }
                        });
                    }
                }
            }
        }, 0, GIFT_CLEAR_TIMER_INTERVAL);
    }

    /**
     * 通过message 遍历 存在就返回  不存在返回null
     *
     * @param message
     * @return
     */
    private static View findViewByMessage(AnimMessage message) {
        for (int i = 0; i < animViewContainer.getChildCount(); i++) {
            AnimMessage giftMessage = (AnimMessage) animViewContainer.getChildAt(i).getTag();
            if (giftMessage.getUserName().equals(message.getUserName()) && giftMessage.getGiftName().equals(message.getGiftName())) {
                return animViewContainer.getChildAt(i);
            }
        }
        return null;
    }

    private static void startGiftAnim(AnimMessage giftMessage) {
        View giftView = findViewByMessage(giftMessage);
        if (giftView == null) {  //如果为空证明该用户不在列表内或者又送了个新礼物
            giftView = addAnimalView(giftMessage);
            animViewContainer.addView(giftView); //将礼物添加到layout布局中
            animViewContainer.invalidate();  //重绘View
        } else {
            //该用户在礼物显示列表内，  连击情况未结束  只需要更新message中的giftNum
            AnimMessage message = (AnimMessage) giftView.getTag();
            message.setGiftNum(message.getGiftNum() + giftMessage.getGiftNum());
            giftView.setTag(message);
            if (message.isComboAnimationOver()) {
                //2.连击动画已经完成,此View还未消失，除了1的操作之外，还需要重启连击动画
                TextView giftNum = giftView.findViewById(R.id.giftNum);
                giftNum.setText("x" + giftNum.getTag());
                ((GiftView) giftView).startComboAnim(giftNum);
            }
        }
    }

    /**
     * 释放资源
     */
    public static void release() {
        if (giftClearTimer != null) {
            giftClearTimer.cancel();
            giftClearTimer = null;
        }

        giftList.clear();
        animViewContainer.removeAllViews();
        giftOutAnim = null;
        mContext = null;
    }


}
